package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.bean.JdContent;
import com.changgou.service.IndexService;
import com.changgou.util.pcUtil;
import com.netflix.discovery.converters.Auto;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private pcUtil pcUtil;

    @Override
    public List<JdContent> parseContent(String keywords) throws Exception{

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        List<JdContent> jdContents = pcUtil.parseDataUrl(keywords);
        for (int i=0;i<jdContents.size();i++){
            bulkRequest.add(new IndexRequest("jd_goods")
                .source(JSON.toJSONString(jdContents.get(i)),XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        if (!bulk.hasFailures()) {
            return jdContents;
        }else{
            return null;
        }


    }
}
